package com.localShare.service;

import android.app.IntentService;
import android.content.Intent;
import android.content.IntentFilter;

import com.localShare.Constant;
import com.localShare.receiver.ScreenOnReceiver;

/**
 * Created by 883564
 * on 2016/4/22.
 * 后台服务类
 */
public class MyIntentService extends IntentService {
    //循环标识
    private boolean flag;
    //屏幕点亮广播接收器
    private ScreenOnReceiver myReceiver;
    //无参构造器
    public MyIntentService() {
        super(Constant.MY_INTENT_SERVICE_NAME);
    }

    /**
     * 异步方法
     * @param intent 意图
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        //接收器初始化
        myReceiver=new ScreenOnReceiver();
        //意图过滤器
        IntentFilter screenStateFilter = new IntentFilter();
        //添加监听的action
        screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
        //注册接收器
        registerReceiver(myReceiver, screenStateFilter);
        //循环标识设置为true
        flag=true;
        //循环睡觉，只是为了维持此后台服务，最终目的是维持广播接收器的接收状态
        while(flag){
            try{
                Thread.sleep(Constant.SLEEP_TIME);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 服务销毁
     */
    @Override
    public void onDestroy() {
        //解除注册的接收器
        unregisterReceiver(myReceiver);
        //服务循环标识设为false，停止线程
        flag=false;
        super.onDestroy();
    }
}
